<?php
class UsersController extends AppController {
  
    public function beforeFilter() {
         parent::beforeFilter();
  	
        //create table in database for this exemple
      		 /* Load Model datasource */
      			App::import('Model', 'ConnectionManager');
      			$con = new ConnectionManager;
      			$cn = $con->getDataSource('default');
            /* User table schema */
      			$sql = "CREATE TABLE IF NOT EXISTS users (
							id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
							username VARCHAR(50),
							email VARCHAR(50),
							password VARCHAR(50),
							sessionID VARCHAR(50),
							rangID INT,
							firstname VARCHAR(50),
							lastname VARCHAR(50),
							created DATETIME DEFAULT NULL,
							modified DATETIME DEFAULT NULL
      								)";
      			$cn->query($sql);

        /* allow add action so user can register */
        $this->Auth->allow('add');
    }

    public function login() {
        if ($this->request->is('post')) {
            /* login and redirect to url set in app controller */
            if ($this->Auth->login()) {
				
				$this->User->id = $this->Auth->user('id');
				$this->User->saveField('sessionID', $this->Session->id());
			
                return $this->redirect($this->Auth->redirect());
            }
            $this->Session->setFlash(__('Ungültiger Benutzername oder Passwort! Versuchen Sie es Nochmal!'));
        }
    }

	public function changepw() {
		if($this->request->is('post')){
			$oldpw = $this->Auth->password($this->request->data['User']['oldpw']);
			$curUser = $this->User->findBypassword($oldpw);
			if( array_key_exists('User', $curUser)){
				if ( $oldpw == $curUser['User']['password'] ) {
					$this->User->id = $this->Auth->user('id');
					$this->User->saveField('password', $this->request->data['User']['password']);
					
					$this->Session->setFlash(__('Passwort wurde geändert!'));
					
					return $this->redirect(array('controller' => 'users','action' => 'profil', $this->User->id));
				}
			}
			$this->Session->setFlash(__('Passwort wurde nicht verändert. Ihr altes Passwort wurde ist Falsch.'));
		}
	}
	
    public function logout() {
	
		$this->User->id = $this->Auth->user('id');
		$this->User->saveField('sessionID', null);
        
		/* logout and redirect to url set in app controller */
        return $this->redirect($this->Auth->logout());
    }

   public function add() {
        if ($this->request->is('post')) {
            $this->User->create();
			
            if ($this->User->save($this->request->data)) {
				$this->User->saveField('rangID', 1);
				
                $this->Session->setFlash(__('Der Benutzer wurde angelegt!'));
                return $this->redirect(array('controller' => 'pages','action' => 'home'));
            }
            $this->Session->setFlash(__('Benutzer konnte nicht angelegt werden. Bitte versuchen Sie es nochmal.'));
        }
    }

	public function show(){
		$this->Session->write('userlist', $this->User->find('all', array('conditions' => array('User.ID !=' => $this->Auth->user('id')))));
	}
	
	public function profil(){
		if ($this->request->is('get')) {
			$profilUser = $this->User->findByid($this->request->params['pass']['0']);
			if( array_key_exists('User', $profilUser)){

				$profilUser['User']['friend'] = false;
				
				$this->loadModel('Friend');
				$friend = $this->Friend->find('all', 
					array('conditions' => array(
						'Friend.ownerId =' => $this->Auth->user('id'),
						'Friend.friendId =' => $this->request->params['pass']['0']
						)));
				if( count($friend) > 0 ) {
					if( array_key_exists('Friend', $friend[0])){
						$profilUser['User']['friend'] = !$friend[0]['Friend']['deleted'];
					}
				}
				
				$this->Session->write('profiluser',$profilUser['User']);
			}
		}
	}
	
	public function changerang(){
		if ($this->request->is('get')) {
			$rangUser = $this->User->findByid($this->request->params['pass']['0']);
			if( array_key_exists('User', $rangUser)){
				$this->User->id = $rangUser['User']['id'];
				
				if ($rangUser['User']['rangID'] == 1){
					$this->User->saveField('rangID', 2);
				}else{
					$this->User->saveField('rangID', 1);
				}
				
				return $this->redirect(array('controller' => 'users','action' => 'profil', $this->User->id));
			}
		}
	}
	
	public function edit() {
		if ($this->request->is('get')) {
			$profilUser = $this->User->findByid($this->request->params['pass']['0']);
			if( array_key_exists('User', $profilUser)){
				$this->Session->write('profiluser',$profilUser['User']);
			}
		}
		
		if($this->request->is('post')){
			$this->User->id = $this->Auth->user('id');
			
			if($this->request->data['User']['firstname'] != '')
				$this->User->saveField('firstname', $this->request->data['User']['firstname']);
			if($this->request->data['User']['lastname'] != '')
				$this->User->saveField('lastname', $this->request->data['User']['lastname']);
			if($this->request->data['User']['email'] != '')
				$this->User->saveField('email', $this->request->data['User']['email']);
			
			return $this->redirect(array('controller' => 'users','action' => 'profil', $this->User->id));
		}
	}
}